package com.example.filter;

import com.example.utils.JwtUtils;
import com.example.utils.RedisConstant;
import com.example.utils.SystemConstant;
import com.example.web.system.entity.LiveUser;
import com.example.web.system.entity.SysUser;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;

@Component
public class JwtAuthenticationTokenFilter  extends OncePerRequestFilter {
    @Autowired
    private RedisTemplate<String,Object> redisTemplate;

    @Autowired
    private JwtUtils jwtUtils;


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        //获取token
        String token = request.getHeader("token");
        if(!StringUtils.hasText(token)){
            //方行
            filterChain.doFilter(request,response);
            return;
        }
        //解析token
        Integer userId;
        Integer userType;
        try{
            userId=jwtUtils.getUserIdFromToken(token);
            userType=jwtUtils.getUserTypeFromToken(token);
        }catch (Exception e){
            throw  new RuntimeException("token非法");
        }
        //刷新token和redis有效期
        String refreshToken = jwtUtils.refreshToken(token);
        response.setHeader("Access-Control-Expose-Headers","token");
        response.addHeader("token",refreshToken);

        //判断用户类型，取出对应的用户信息,刷新缓存
        if(userType==SystemConstant.USER_TYPE_WUZHU){
            SysUser sysUser=(SysUser) redisTemplate.opsForValue().get(RedisConstant.LOGIN_SYS_USER_PRE+userId);
            if(Objects.isNull(sysUser)){
                throw new RuntimeException("用户未登录");
            }
            redisTemplate.expire(RedisConstant.LOGIN_SYS_USER_PRE+userId,RedisConstant.LOGIN_SYS_USER_EXPIRE_TIME, TimeUnit.MINUTES);

            //用户信息存入securityContextHolder中
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(sysUser, null, null);
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        } else if (userType==SystemConstant.USER_TYPE_YEZHU) {
            LiveUser liveUser=(LiveUser) redisTemplate.opsForValue().get(RedisConstant.LOGIN_LIVE_USER_PRE+userId);
            if(Objects.isNull(liveUser)){
                throw new RuntimeException("用户未登录");
            }
            redisTemplate.expire(RedisConstant.LOGIN_LIVE_USER_PRE+userId,RedisConstant.LOGIN_LIVE_USER_EXPIRE_TIME, TimeUnit.MINUTES);

            //用户信息存入securityContextHolder中
            UsernamePasswordAuthenticationToken usernamePasswordAuthenticationToken = new UsernamePasswordAuthenticationToken(liveUser, null, null);
            SecurityContextHolder.getContext().setAuthentication(usernamePasswordAuthenticationToken);

        }
        //放行
        filterChain.doFilter(request,response);

    }
}
